package com.txzt.gaea.provide.controller;

import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.flow.model.FlowBizStep;
import com.txzt.gaea.provide.service.biz.FileInfoBizService;
import com.txzt.gaea.provide.utils.LogUtils;
import com.txzt.gaea.provide.utils.SpringContextUtil;
import org.beetl.sql.core.SQLManager;
import org.ofdrw.converter.ImageMaker;
import org.ofdrw.reader.OFDReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/file")
public class FileController {

    @Value("${file.ofd_url}")
    String ofdUrl;

    @Autowired
    private FileInfoBizService fileInfoBizService;


    @RequestMapping("/upload")
    @ResponseBody
    public RtnInfo<Map<String, Object>> upload(MultipartFile file,
                                               @RequestParam(required = false) String fileDesc,
                                               @RequestParam(required = false) String toolCode) throws Exception {
        LogUtils.logSave("file#upload", "文件上传", "com.txzt.gaea.provide.controller.FileController");
        if (file == null) {
            return null;
        }
        return RtnInfo.success(fileInfoBizService.upload(file, fileDesc, toolCode));
    }

    @RequestMapping("/upload/project")
    @ResponseBody
    public RtnInfo projectUpload(MultipartFile file,
                                 @RequestParam(required = false) String projectNo,
                                 @RequestParam(required = false) Integer bizType,
                                 @RequestParam(required = false) String fileDesc,
                                 @RequestParam(required = false) String toolCode) throws Exception {
        LogUtils.logSave("file#upload", "文件上传", "com.txzt.gaea.provide.controller.FileController");
        if (file == null) {
            return null;
        }
        return RtnInfo.success(fileInfoBizService.uploadNew(file, projectNo, bizType, fileDesc, toolCode));
    }

    @PostMapping("/upload/ofd2png")
    @ResponseBody
    public RtnInfo test(@RequestParam(value = "source") MultipartFile file,
                           @RequestParam(value = "bizId") Long bizId) throws Exception {
        LogUtils.logSave("file#upload", "文件上传", "com.txzt.gaea.provide.controller.FileController");
        if (file == null) {
            return null;
        }
        ImageMaker imageMaker = new ImageMaker(new OFDReader(file.getInputStream()), 15);
        imageMaker.config.setDrawBoundary(false);
        Map<String, Object> map1 = new HashMap<>();
        for (int i = 0; i < imageMaker.pageSize(); i++) {
            BufferedImage image = imageMaker.makePage(i);
            int top = 0;
            int left = 0;
            int bottom = image.getHeight();
            int right = image.getWidth();

            //寻找最上面的标线,从左(0)到右，从上(0)到下
            for (int k = 0; k < image.getHeight(); k++)//行
            {
                boolean find = false;
                for (int j = 0; j < image.getWidth(); j++)//列
                {
                    int pixel = image.getRGB(j, k);
                    if (!IsWhite(pixel)) {
                        top = k;
                        find = true;
                        break;
                    }

                }
                if (find)
                    break;
            }
            //寻找最左边的标线，从上（top位）到下，从左到右
            for (int k = 0; k < image.getWidth(); k++)//列
            {
                boolean find = false;
                for (int j = top; j < image.getHeight(); j++)//行
                {
                    int pixel = image.getRGB(k, j);
                    if (!IsWhite(pixel)) {
                        left = k;
                        find = true;
                        break;
                    }
                }
                if (find)
                    break;
            }
            //寻找最下边标线，从下到上，从左到右
            for (int k = image.getHeight() - 1; k >= 0; k--)//行
            {
                boolean find = false;
                for (int j = left; j < image.getWidth(); j++)//列
                {
                    int pixel = image.getRGB(j, k);
                    if (!IsWhite(pixel)) {
                        bottom = k;
                        find = true;
                        break;
                    }
                }
                if (find)
                    break;
            }
            //寻找最右边的标线，从上到下，从右往左
            for (int k = image.getWidth() - 1; k >= 0; k--)//列
            {
                boolean find = false;
                for (int j = 0; j <= bottom; j++)//行
                {
                    int pixel = image.getRGB(k, j);
                    if (!IsWhite(pixel)) {
                        right = k;
                        find = true;
                        break;
                    }
                }
                if (find)
                    break;
            }
            BufferedImage sdf = image.getSubimage(left, top, right - left, bottom - top);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(sdf, "jpg", out);
            MultipartFile multipartFile = new MockMultipartFile("temp.jpg","temp.jpg","jpg",out.toByteArray());
            map1 = fileInfoBizService.upload(multipartFile, null, null);
        }
        SQLManager sqlManager = (SQLManager)SpringContextUtil.getBean(SQLManager.class);
        FlowBizStep flowBizStep = new FlowBizStep();
        flowBizStep.setId(bizId);
        flowBizStep.setESignature(map1.get("fileUrl").toString());
        return RtnInfo.success(sqlManager.updateTemplateById(FlowBizStep.class,flowBizStep));
    }

    /**
     * 判断是否白色（10点的容差）
     * @param pixel
     * @return
     */
    public boolean IsWhite(int pixel) {
        int[] rgb = new int[3];
        rgb[0] = (pixel & 0xff0000) >> 16; //r
        rgb[1] = (pixel & 0xff00) >> 8; //g
        rgb[2] = (pixel & 0xff); //b
        //RGB都为255为纯白
        if (rgb[0] > 245 && rgb[1] > 245 && rgb[2] > 245)
            return true;
        return false;
    }

    @RequestMapping("/ofd")
    @ResponseBody
    public RtnInfo<Map<String, Object>> ofdUpload(MultipartFile file,
                                                  @RequestParam(required = false) String filePath,
                                                  @RequestParam(required = false) String fileName) throws Exception {
        if (file == null) {
            return null;
        }
        fileInfoBizService.upload(file, null, null);
        String imgPath = toPng(filePath+fileName, filePath, fileName);

        return RtnInfo.success(imgPath);
    }

    public String toPng(String filename, String dirPath, String jpgName) throws IOException {
        //filename文件路径到文件名
        Path src = Paths.get(filename);
        ImageMaker imageMaker = new ImageMaker(new OFDReader(src), 15);
        imageMaker.config.setDrawBoundary(false);
        String imgName = "";
        for (int i = 0; i < imageMaker.pageSize(); i++) {
            BufferedImage image = imageMaker.makePage(i);
            //文件要存的路径 第二个是文件名
            imgName = jpgName.split("\\.")[0];
            Path dist = Paths.get(dirPath, imgName + ".jpg");
            ImageIO.write(image, "PNG", dist.toFile());
        }
        return dirPath + imgName + ".jpg";
    }

    @GetMapping("/open/ofd")
    public void openOfd(HttpServletResponse response) throws Exception{
//        response.setHeader("Content-Length",String.valueOf());
        response.setHeader("Content-Type","application/pdf");
        response.sendRedirect(ofdUrl);
    }
}
